package com.etone.smartAudit.utils;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: sovy
 * @date: 2020/8/20
 * @description:
 */
public class ImageUtil {

    /**
     * 正则提取对象的图片地址
     *
     * @param obj
     * @return
     */
    public static List<String> regFileJsonUrl(Object obj) {
        List<String> urls = new ArrayList();
        String objJson = obj instanceof String ? String.valueOf(obj) : JSON.toJSONString(obj);
        String regex = "(\\s*)\\\"url\\\"(\\s*):(\\s*)\\\"(.+?)\\\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(objJson);

        //可能存在(\")格式
        String regex1 = "(\\s*)\\\\\"url\\\\\"(\\s*):(\\s*)\\\\\"(.+?)\\\\\"";
        Pattern pattern1 = Pattern.compile(regex1);
        Matcher matcher1 = pattern1.matcher(objJson);


        while (matcher.find()) {
            String url = matcher.group(4);
            if (!StringUtils.isEmpty(url)) {
                urls.add(url);
            }
        }

        while (matcher1.find()) {
            String url = matcher1.group(4);
            if (!StringUtils.isEmpty(url)) {
                urls.add(url);
            }
        }
        return urls;
    }

    /**
     * 获取富文本中的img标签的url地址
     *
     * @param htmls
     * @return
     */
    public static List<String> getImgTagUrl(String... htmls) {
        List<String> urls = new ArrayList();
        if (htmls != null && htmls.length > 0) {
            for (String html : htmls) {
                if (!StringUtils.isEmpty(html)) {
                    Document parse = Jsoup.parse(html);
                    Elements imgTags = parse.getElementsByTag("img");
                    imgTags.forEach(imgTag -> {
                        urls.add(imgTag.attr("src"));
                    });
                }
            }

        }

        return urls;
    }
}
